package mi.payment.utils.transaction;

import android.text.TextUtils;

import com.sunmi.pay.hardware.aidlv2.AidlConstantsV2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lainey.ui.utils.LogUtil;
import mi.payment.Constant;
import mi.payment.MyApplication;
import mi.payment.db.dao.PayDetail;
import mi.payment.utils.ByteUtil;
import mi.payment.utils.iso8583.MsgField;
import mi.payment.utils.iso8583.TLV;
import mi.payment.utils.iso8583.TLVUtils;

public class AuthorizationProcessTools {

    private PayDetail dbBean;
    private HashMap<String, MsgField> resp;

    public static void authorizationProcess(HashMap<String, MsgField> respArgs, PayDetail dbBeanArgs) {
        AuthorizationProcessTools processTools = new AuthorizationProcessTools(respArgs, dbBeanArgs);
        processTools.authorizationProcess();
    }

    public AuthorizationProcessTools(HashMap<String, MsgField> respArgs, PayDetail dbBeanArgs) {
        this.resp = respArgs;
        this.dbBean = dbBeanArgs;
    }

    /**
     * 二次授权处理与处理结果上送
     */
    private void authorizationProcess() {
        // 二次授权处理与处理结果上送
        MsgField field38 = null;
        MsgField field39 = null;
        MsgField field55 = null;
        if (resp != null) {
            field38 = resp.get("F038");
            field39 = resp.get("F039");
            field55 = resp.get("F055");
        }
        int isCommunicated = 1;

        boolean f038Valid = field38 != null && field38.getDataStr() != null && field38.getDataStr().length() > 0;
        boolean f039Valid = field39 != null && field39.getDataStr() != null && field39.getDataStr().length() > 0;
        boolean f055Valid = field55 != null && field55.getDataStr() != null && field55.getDataStr().length() > 0;
        if (f039Valid || f055Valid || f038Valid) {
            isCommunicated = 0;
        }
        if (isCommunicated == 0) {
            // 响应码
            String valueF039 = null;
            if (f039Valid) {
                byte[] dataBytes = field39.getDataBytes();
                valueF039 = ByteUtil.bytes2HexStr(dataBytes);
                // setTlv("8A", valueF039);
            }

            // 授权码
            String valueF038 = null;
            if (f038Valid) {
                byte[] dataBytes = field38.getDataBytes();
                valueF038 = ByteUtil.bytes2HexStr(dataBytes);
                // setTlv("89", valueF038);
            }

            String value71 = null;
            String value72 = null;
            String value91 = null;
            if (f055Valid) {
                String f55 = field55.getDataStr();
                Map<String, String> tlvMap = TLVUtils.builderAuthorizationProcessMap(f55);
                value71 = tlvMap.get("71");
                if (value71 != null && value71.length() > 0) {
                    value71 = value71.substring(4);
                    dbBean.setScriptUploadStatus(1);
                    dbBean.setScript1Content(value71);
                    // setTlv("71", value71);
                }
                value72 = tlvMap.get("72");
                if (value72 != null && value72.length() > 0) {
                    value72 = value72.substring(4);
                    dbBean.setScriptUploadStatus(1);
                    dbBean.setScript2Content(value72);
                    // setTlv("72", value72);
                }
                value91 = tlvMap.get("91");
                if (value91 != null && value91.length() > 0) {
                    value91 = value91.substring(4);
                    dbBean.setIssuerVerifyData(value91);
                    // setTlv("91", value91);
                }
            }

            boolean equals = TextUtils.equals("3030", valueF039);
            List<String> tagList = new ArrayList<>();
            List<String> valueList = new ArrayList<>();
            if (valueF039 != null && valueF039.length() > 0) {
                tagList.add("8A");
                valueList.add(valueF039);
            }
            if (valueF038 != null && valueF038.length() > 0) {
                tagList.add("89");
                valueList.add(valueF038);
            }
            if (value71 != null && value71.length() > 0) {
                tagList.add("71");
                valueList.add(value71);
            }
            if (value72 != null && value72.length() > 0) {
                tagList.add("72");
                valueList.add(value72);
            }
            if (value91 != null && value91.length() > 0) {
                tagList.add("91");
                valueList.add(value91);
            }
            int size = tagList.size();
            byte[] outData = new byte[24];
            String[] tags = new String[size];
            String[] hexValues = new String[size];
            for (int i = 0; i < tagList.size(); i++) {
                String tag = tagList.get(i);
                String value = valueList.get(i);
                tags[i] = tag;
                hexValues[i] = value;
            }
            int status;
            if (equals) {
                // Approval
                status = importOnlineProcessStatus(0, tags, hexValues, outData);
            } else {
                equals = TextUtils.equals("3035", valueF039) || TextUtils.equals("3531", valueF039);
                if (equals) {
                    // Denial
                    status = importOnlineProcessStatus(1, tags, hexValues, outData);
                } else {
                    // Failed
                    status = importOnlineProcessStatus(2, tags, hexValues, outData);
                }
            }
            LogUtil.e(Constant.TAG, "status: " + status);

            String scriptResult = ByteUtil.bytes2HexStr(outData);
            LogUtil.e(Constant.TAG, "scriptResult: " + scriptResult);
            dbBean.setScriptResult(scriptResult);

            String f055Data = getF055Data();
            LogUtil.e(Constant.TAG, "f055Data: " + f055Data);

            if (status >= 0) {
                dbBean.setConfirmBag(f055Data);
                fillICParams();
            } else {
                dbBean.setReversalBag(f055Data);
                dbBean.setTradeAnswerCode(Constant.ANSWER_CODE_SCRIPT);
                dbBean.isNeedReversal = true;
            }
        }
    }

    private int importOnlineProcessStatus(int status, String[] tags, String[] hexValues, byte[] outData) {
        LogUtil.e(Constant.TAG, "importOnlineProcessStatus status:" + status);
        try {
            int result = MyApplication.getInstance().mEMVOptV2.importOnlineProcStatus(status, tags, hexValues, outData);
            LogUtil.e(Constant.TAG, "result: " + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -100;
    }

    private String getF055Data() {
        String[] tagList = {
                "DF02", "5F34", "9F06", "FF30", "FF31", "95", "9B", "8A",
                "9F36", "9F26", "9F27", "DF31", "5A", "57", "5F24", "9F1A", "9F03", "9F33",
                "9F10", "9F37", "9C", "9A", "9F02", "5F2A", "82", "9F34", "9F35", "9F1E",
                "84", "4F", "9F09", "9F41", "9F63", "50", "9F08", "9F0E", "9F0F", "9F0D"
        };
        byte[] outData = new byte[2048];
        try {
            int len = MyApplication.getInstance().mEMVOptV2.getTlvList(AidlConstantsV2.EMV.TLVOpCode.OP_NORMAL, tagList, outData);
            if (len > 0) {
                byte[] data = new byte[len];
                System.arraycopy(outData, 0, data, 0, len);
                return ByteUtil.bytes2HexStr(data);
            } else {
                LogUtil.e(Constant.TAG, "获取55域的数据长度为负数 = " + len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 回填确认包数据到IC卡参数
     */
    private void fillICParams() {
        if (dbBean.confirmBag == null || dbBean.confirmBag.length() == 0) return;

        Map<String, TLV> tlvMap = TLVUtils.builderTLVMap(dbBean.confirmBag);

        // 密码密文
        TLV tlv = tlvMap.get("DF02");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setPINCipher(value);
        }

        // 主账号序号（针对IC卡）
        String panSubNo = "000";
        tlv = tlvMap.get("5F34");
        if (tlv != null) {
            try {
                String value = tlv.getValue();
                int parseInt = Integer.parseInt(value);
                panSubNo = String.format("%03d", parseInt);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        dbBean.setCardSerialNo(panSubNo);

        // AID
        tlv = tlvMap.get("9F06");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setAID(value);
        }

        // 应用标签
        tlv = tlvMap.get("FF30");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setAppLabel(value);
        }

        // 应用首选名称
        tlv = tlvMap.get("FF31");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setAppName(value);
        }

        // TVR
        tlv = tlvMap.get("95");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setTVR(value);
        }

        // TSI
        tlv = tlvMap.get("9B");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setTSI(value);
        }

        // ATC
        tlv = tlvMap.get("9F36");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setATC(value);
        }

        // TC
        tlv = tlvMap.get("9F26");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setTC(value);
        }

        // 脚本处理结果
        tlv = tlvMap.get("DF31");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setScriptResult(value);
        }

        // 密文信息数据
        tlv = tlvMap.get("9F27");
        if (tlv != null) {
            String value = tlv.getValue();
            dbBean.setCID(value);
        }
    }


}